package com.dragon.logical.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.DateNumUtils;
import com.dragon.logical.service.customer.IGoodsService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.Goods;
import com.dragon.repository.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

/**
 * <p>
 * 产品 表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-30
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    GoodsMapper mapper;

    @Override
    @DataScope(adminAlias = "", adminField = "admin_id", deptAlias = "", deptField = "department_id")
    public Page<Goods> goodsList(Integer page, Integer limit, String search) {
        Page<Goods> goodsPage = new Page<>(page, limit);
        return mapper.goodsList(goodsPage, search);
    }

    @Override
    public Integer addGoods(Goods goods) {
        if (mapper.selectById(goods.getId()) != null){
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }

        goods.setCreateTime(DateUtil.date());
        //自动生成编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String code = "CP-" + sdf.format(goods.getCreateTime());
        String maxCode =  mapper.maxRoundInoutNumber(code);
        String newCode = null;
        if (StrUtil.isEmpty(maxCode)){
            newCode = code + "01";
        }
        else {
            String getMaxCode = maxCode.substring(11, 13);
            newCode = code + DateNumUtils.getNum(getMaxCode);
        }
        goods.setGoodsNum(newCode);

        mapper.insert(goods);
        return goods.getId();
    }

    @Override
    public void updateGoods(Goods goods){
        Goods other = mapper.selectById(goods.getId());
        if (other == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        goods.setUpdateTime(DateUtil.date());
        mapper.updateById(goods);
    }

    @Override
    public void deleteGoods(Integer id){
        Goods goods = new Goods();
        goods.setDeleted(1);
        goods.setUpdateTime(DateUtil.date());
        mapper.update(goods,new QueryWrapper<Goods>().lambda()
                .eq(Goods::getId,id));
    }
}
